let _ = require('lodash');
let config = require('../config');
let settingModel = require('../models/setting.model');


/**
 * 检测request中的参数
 */
function checkSettingReq(req, res) {
    let key = req.body.key;
    let name = req.body.name;
    let type = req.body.type;

    let string = req.body.string;
    let int = req.body.int;
    let bool = req.body.bool;
    let array = req.body.array;
    let json = req.body.json;

    if (_.isNil(string))
        string = '';

    if (_.isNil(int))
        int = 0;

    if (_.isNil(bool))
        bool = false;

    if (_.isNil(array))
        array = [];

    if (_.isNil(json))
        json = {};

    if (_.isNil(key) || _.isEmpty(key) || _.isNil(name) || _.isEmpty(name) || _.isNil(type) || !_.isNumber(type)) {
        res.jsonFail('数据格式错误!');
        return null;
    }
    type = _.toInteger(type);
    if (type < 0 || type > 4) {
        res.jsonFail('存储类型错误!');
        return null;
    }

    return {
        key: key,
        name: name,
        type: type,
        string: string,
        int: int,
        bool: bool,
        array: array,
        json: json,
    };
}

module.exports = {
    /**
     * 获取设置列表
     * @param req
     * @param res
     * @param next
     */
    settings(req, res, next) {
        settingModel.findAll().then(ss => {
            res.jsonSuccess(ss);
        }).catch(e => {
            res.jsonFail(e.message);
        });
    },

    /**
     * 增加设置项
     * @param req
     * @param res
     * @param next
     */
    add(req, res, next) {
        let result = checkSettingReq(req, res);
        if (_.isNil(result)) {
            return;
        }
        settingModel.findOne({attributes: ['key'], where: {key: result.key}}).then(s => {
            if (s) {
                res.jsonFail(`配置 ${result.key} 已经存在！`);
            } else {
                result.builtIn = false;
                return settingModel.create(result).then(s => {
                    config.system[s.key] = s.value();
                    res.jsonSuccess();
                }).catch(e => {
                    res.jsonFail(e.message);
                });
            }
        }).catch(e => {
            res.jsonFail('系统错误！');
        });
    },

    /**
     * 更新设置项
     * @param req
     * @param res
     * @param next
     */
    update(req, res, next) {
        let result = checkSettingReq(req, res);
        if (_.isNil(result)) {
            return;
        }
        settingModel.findOne({attributes: ['type', 'key', 'builtIn'], where: {key: result.key}}).then(s => {
            if (!s) {
                res.jsonFail(`配置 ${result.key} 不存在！`);
                return;
            }
            for (let key in result) {
                if (key === 'key') {
                    continue;
                }
                if (s.builtIn && (key === 'type' || key === 'name')) {
                    continue;
                }
                s[key] = result[key];
            }
            return s.save().then(s => {
                config.system[s.key] = s.value();
                res.jsonSuccess();
            }).catch(e => {
                res.jsonFail(e.message);
            });
        }).catch(e => {
            res.jsonFail('系统错误！');
        });
    },


    /**
     * 删除设置项
     * @param req
     * @param res
     * @param next
     */
    del(req, res, next) {
        let key = req.body.key;

        if (_.isNil(key) || _.isEmpty(key)) {
            res.jsonFail('key不能为空!');
            return;
        }
        settingModel.findOne({attributes: ['key', 'builtIn'], where: {key: key}}).then(s => {
            if (!s) {
                res.jsonFail(`配置 ${key} 不存在！`);
                return;
            }
            if (s.builtIn) {
                res.jsonFail(`系统内置配置 ${key} 不可删除！`);
                return;
            }
            return s.destroy().then(
                s => {
                    delete config.system[s.key];
                    res.jsonSuccess();
                },
            ).catch(e => {
                    res.jsonFail(`系统错误！`);
                },
            );
        }).catch(e => {
            res.jsonFail('系统错误！');
        });
    },
};
